<template>
    <div>
      <div class="container">
        <el-page-header @back="goBack" content="创建出库单"></el-page-header>
        <el-form :model="form" :rules="rules" ref="form" label-width="160px" class="e-m-t-45">
          <div class="flex">
            <div class="e-flex-1">
              <el-form-item label="站点" prop="storeid">
                <el-select 
                  v-model="form.storeid" 
                  placeholder="请选择站点"
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="getStoreList"
                >
                  <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="e-flex-1">
              <el-form-item label="打包站" prop="packstationid">
                <el-select 
                  v-model="form.packstationid" 
                  placeholder="请选择打包站"
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="getPackStation"
                >
                  <el-option v-for="item in packStationList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            
          </div>
          <div class="flex">
            <div class="e-flex-1">
              <el-form-item label="需求出库时间" prop="demandtime">
                <el-date-picker v-model="form.demandtime" type="datetime" style="width:100%"
                  value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
            </div>
            <div class="e-flex-1">
              <el-form-item label="运送小哥" prop="brotherid">
                <el-select 
                  v-model="form.brotherid" 
                  placeholder="请选择运送小哥" 
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="getBrother"
                >
                  <el-option 
                    v-for="item in brotherList" 
                    :key="item.id" 
                    :label="`${item.name}`" 
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="flex">
            <div class="e-flex-1">
              <el-form-item label="备注">
                <el-input type="textarea" v-model="form.remark" rows="4"></el-input>
              </el-form-item>
            </div>
          </div>
          <div class="flex">
            <div class="e-flex-1">
              <el-form-item label="出库证明" prop="proves">
                <div class="images-list">
                  <div class="item" v-for="(item, index) in form.proves" :key="index">
                    <el-image style="width: 150px; height: 150px; border-radius: 6px;" :src="fileURL + item"
                      :preview-src-list=[[fileURL+item]] fit="cover"></el-image>
                    <span class="el-icon-error err" @click.stop="delFile(index)"></span>
                    <!-- <span class="el-icon-download e-p-15" @click.stop="previewFiles(fileURL + item.savename)"></span>
                    <span class="el-icon-error err" @click.stop="delFile(index)"></span> -->
                  </div>
                  <div class="item">
                    <cropper-upload @getUpload="handleFilesSuccess" class="avatar-uploader">
                      <div class="avatar-uploader-icon">
                        <div><i class="el-icon-plus"></i></div>
                      </div>
                    </cropper-upload>
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
          <div class="e-m-b-30">
            <h4>库存</h4>

            <el-table 
              ref="multipleTable" 
              tooltip-effect="dark" 
              :data="stockList"
              :span-method="objectSpanMethod" 
              stripe 
              border 
              style="width: 100%; margin-top: 20px"
              v-loading="loading"
            >
                <el-table-column prop="large" label="类型" width="200">
                  <template slot-scope="scope">
                    <h4 class="text-center">{{ scope.row.large }}</h4>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="小类" width="200">
                </el-table-column>
                <el-table-column prop="weight" label="库存数量">
                  <template slot-scope="scope">
                      <span>{{ scope.row.weight}}{{ scope.row.isweighing?'KG':'件'}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="出库数量" width="202">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.num" controls-position="right" @change="numberChange" :min="0" :max="scope.row.weight" label="请填写出库数量"></el-input-number>
                    <!-- <el-input type="number" v-model="scope.row.num" placeholder="请填写出库数量" :min="0" :max="scope.row.weight" @blur="numberChange($event,scope.row.weight,scope.row.id)"></el-input> -->
                    <!-- <div class="e-tips-color"><i class="el-icon-warning"></i>输入范围在0-{{scope.row.weight}}KG范围内</div> -->
                  </template>
                </el-table-column>
                <el-table-column label="备注">
                    <template slot-scope="scope">
                      <el-input type="text" v-model="scope.row.remark" placeholder="请填写备注"></el-input>
                    </template>
                </el-table-column>
            </el-table>
          </div>

          <el-form-item label-width="0">
            <el-button @click="goBack">返回</el-button>
            <el-button type="primary" @click="createStorage">创建</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </template>
  
  <script>
    export default {
      layout: 'admin',
      head() {
        return {
          title: '创建出库单' 
        }
      },
      data() {
        return {
          loading: false,
          form: {
            storeid: '',
            packstationid: '',
            brotherid: '',
            demandtime: null,
            deliverdetails: [
              // {
              //     id: 0,
              //     weight: 0
              //     typeRemarks: "string",
              // }
            ],
            proves: [
              
            ],
            remark: ''
          },
          rules: {
            storeid:[{
              required: true,
              message: '请选择站点',
              trigger: 'change'
            }],
            packstationid:[{
              required: true,
              message: '请选择打包站',
              trigger: 'change'
            }],
            brotherid:[{
              required: true,
              message: '请选择小哥',
              trigger: 'change'
            }],
            demandtime:[{
              required: true,
              message: '请选择需求出库时间',
              trigger: 'change'
            }],
            proves:[
              { type: 'array', required: true, message: '请至少上传一张出库正面照片', trigger: 'change' }
            ],
            deliverdetails: [
              { type: 'array', required: true, message: '请至少设置一种出库品类', trigger: 'change' }
            ]
          },
          brotherList: [], //可选小哥列表
          packStationList: [], //打包站列表
          storeList: [], //站点列表
          stockList:[]
        }
      },
      watch: {
        "form.storeid"(id){
          if(id > 0){
            this.getStock(id)
          }
        }
      },
      mounted() {
        this.getBrother()
        this.getPackStation()
        this.getStoreList()
      },
      methods: {
        goBack() {
          this.$router.go(-1)
        },
        numberChange(e,max,id){
          // console.log(e.target.value)
          // let value = parseFloat(e.target.value)
          // if(value > max){ //输入数字大于库存时
          //   // this.stockList.filter(item=>item.typepath == id)[0].issue = max
          // }else if(max < 0){
          //   // this.stockList.filter(item=>item.typepath == id)[0].issue = 0
          // }
  
          // this.$forceUpdate()
        },
        getStock(id){ //获取库存
          this.loading = true
          this.$axios.get('/Admin/Store/Stock/List?id='+id).then((res) => {
            console.log(res)
            this.loading = false
            let dataArr = []
            res.forEach(item => {
                item.details.forEach(i => {
                    let obj = {}
                    obj.id = i.typepath
                    obj.name = i.typenames
                    obj.isweighing = i.isweighing
                    obj.weight = i.weight
                    obj.large = item.typeNames
                    obj.bigid = item.typeId
                    obj.num = 0 //出库数量
                    obj.remarks = '' //备注
                    dataArr.push(obj)
                })
            });
            this.stockList = dataArr
          }).catch(()=>{
            this.loading = false
          })
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            let mergeLength = 1;//需要进行横纵合并的列
            if (columnIndex < mergeLength) {
                let finArray = [1, 1];
                // 处理行数据
                let cgname = Object.keys(row)[5]//0是数字最后一项类型id
                if (rowIndex === 0 || row[cgname] !== this.stockList[rowIndex - 1][cgname]) {
                    let rowspan = 1;
                    //计算需要进行合并操作的行
                    for (let i = 0; i < this.stockList.length - 1; i++) {
                        // 只合并连续的
                        if (this.stockList[i][cgname] === row[cgname] && this.stockList[i + 1][cgname] === row[cgname]) {
                            rowspan++;
                        }
                    }
                    finArray[0] = rowspan;
                } else {
                    finArray[0] = 0;
                }
                return finArray
            }
        },
        getBrother(key = '') { //获取小哥列表
          this.$axios.post('/Admin/Brother/Account/List',{
            "PageIndex": 1,
            "PageSize": 20,
            "Key": key
          }).then((res) => {
            console.log(res)
            this.brotherList = res.rows
          })
        },
        getPackStation(key = '') { //获取打包站列表
          this.$axios.post('/Admin/PackStation/Account/List',{
            "PageIndex": 1,
            "PageSize": 20,
            "Key": key
          }).then((res) => {
            console.log(res)
            this.packStationList = res.rows
          })
        },
        getStoreList(key = ''){ //获取站点列表
          this.$axios.post('/Select/StoreList',{
            "PageIndex": 1,
            "PageSize": 20,
            "Key": key
          }).then((res) => {
            console.log(res)
            this.storeList = res.rows
          })
        },
        handleFilesSuccess(res, file) {
          this.form.proves.push(res.path);
          this.$refs.form.validate()
        },
        previewFiles(url) {
          window.open(url)
        },
        delFile(index) {
          this.form.proves.splice(index, 1);
        },
        // 创建出库单
        createStorage() {
          this.$refs.form.validate((valid) => {
            if (valid) {
              this.form.deliverdetails = []
              this.stockList.forEach((item) => {
                if(item.num > 0){
                  this.form.deliverdetails.push({
                    id: item.id,
                    weight: item.num,
                    typeRemarks: item.remark
                  })
                }
              })
  
              console.log(this.form)
              this.$axios.post('/Admin/Store/CreateStoreOrder', this.form).then((res) => {
                this.$message.success('出库成功');
                this.$router.push({
                  path:'/order/store/list'
                })
              })
            } else {
              console.log('error submit!!');
              return false;
            }
          });
        }
      }
    }
  </script>
  
  <style lang="scss" scoped>
    .e-tips-color{
      font-size: 12px;
      color: var(--grey);
    }
    .images-list {
      display: flex;
  
      .item {
        padding-right: 15px;
        position: relative;
  
        .el-icon-error {
          position: absolute;
          top: -8px;
          right: 7px;
          font-size: 22px;
          color: var(--red);
          background: #fff;
          border-radius: 50%;
          cursor: pointer;
  
          &:hover {
            color: #f00;
          }
        }
      }
    }
  </style>
  